# zbx_itemctl/client.py
import os
import requests
from typing import Any, Dict

class ZabbixAPIError(Exception):
    pass

class ZabbixClient:
    def __init__(self, url: str, user: str, password: str):
        self.url = url.rstrip("/")
        self.session = requests.Session()
        self._auth = None
        self._login(user, password)

    def _login(self, user: str, password: str) -> None:
        payload = {
            "jsonrpc": "2.0",
            "method": "user.login",
            "params": {"username": user, "password": password},
            "id": 1,
        }
        resp = self.session.post(self.url, json=payload, timeout=10)
        data = resp.json()
        if "error" in data:
            raise ZabbixAPIError(data["error"])
        self._auth = data["result"]

    def call(self, method: str, params: Dict[str, Any] = None) -> Any:
        payload = {
            "jsonrpc": "2.0",
            "method": method,
            "params": params or {},
            "auth": self._auth,
            "id": 2,
        }
        resp = self.session.post(self.url, json=payload, timeout=10)
        data = resp.json()
        if "error" in data:
            raise ZabbixAPIError(data["error"])
        return data["result"]